package com.tangkun.environment.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.GroundOverlayOptions;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.search.core.CityInfo;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiBoundSearchOption;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.poi.PoiSortType;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import com.tangkun.environment.R;
import com.tangkun.environment.adapter.LocationDemo3Adapter;
import com.tangkun.environment.entity.gongzuo.DepartmentAreaReturn;
import com.tangkun.environment.utils.JumpHelper;
import com.tangkun.environment.utils.LogUtils;
import com.tangkun.environment.utils.Utils;
import com.tangkun.environment.utils.overlayutil.PoiOverlay;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 详细地址
 * 此demo用来展示如何结合定位SDK实现定位，并使用MyLocationOverlay绘制定位位置 同时展示如何使用自定义图标绘制并点击时弹出泡泡
 */
public class LocationDemo3 extends BaseActivity implements SensorEventListener, OnGetPoiSearchResultListener, OnGetSuggestionResultListener {

    // 定位相关
    LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.next)
    TextView next;
    private LocationMode mCurrentMode;
    BitmapDescriptor mCurrentMarker;
    private static final int accuracyCircleFillColor = 0xAAFFFF88;
    private static final int accuracyCircleStrokeColor = 0xAA00c27b;
    private SensorManager mSensorManager;
    private Double lastX = 0.0;
    private int mCurrentDirection = 0;
    //纬度
    private double mCurrentLat = 0.0;
    //经度
    private double mCurrentLon = 0.0;
    //城市
    private String mCurrentCity = "";
    private float mCurrentAccracy;

    MapView mMapView;
    BaiduMap mBaiduMap;

    // UI相关
    OnCheckedChangeListener radioButtonListener;
    boolean isFirstLoc = true; // 是否首次定位
    private MyLocationData locData;
    private float direction;

    private ItemizedOverlay itemizedOverlay;

    private PoiSearch mPoiSearch = null;
    private SuggestionSearch mSuggestionSearch = null;
    private List<String> suggest;
    private List<SuggestionResult.SuggestionInfo> searchResultList;
    /**
     * 搜索关键字输入窗口
     */
//    private EditText editCity = null;
    private AutoCompleteTextView keyWorldsView = null;
    //    private ArrayAdapter<String> sugAdapter = null;
    private LocationDemo3Adapter searchResultListAdapter = null;
    private int loadIndex = 0;

    LatLng center = new LatLng(39.92235, 116.380338);
    int radius = 100;
    LatLng southwest = new LatLng(39.92235, 116.380338);
    LatLng northeast = new LatLng(39.947246, 116.414977);
    LatLngBounds searchbound = new LatLngBounds.Builder().include(southwest).include(northeast).build();

    int searchType = 0;  // 搜索的类型，在显示时区分

    //经纬度和详细地址
    String latitude = "";
    String longitude = "";
    String address = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location3);
        ButterKnife.bind(this);
        title.setText("详细地址");
        next.setText("确定");
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);//获取传感器管理服务

        // 地图初始化
        mMapView = (MapView) findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();
        // 隐藏缩放按钮
        mMapView.showZoomControls(false);
        // 设置地图缩放范围100米和20公里
//        mMapView.getMap().setMaxAndMinZoomLevel(17.0f, 11.0f);
        // 删除百度地图logo
        mMapView.removeViewAt(1);

        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位初始化
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(30 * 1000);//检查周期 小于1秒的按1秒
        mLocClient.setLocOption(option);
        mLocClient.start();

        //设置模式
        mCurrentMode = LocationMode.NORMAL;
        mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                mCurrentMode, true, mCurrentMarker));
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.overlook(0);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

        // 修改为自定义marker
        mCurrentMarker = BitmapDescriptorFactory
                .fromResource(R.mipmap.ic_ditu_dingweidian);
        mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                mCurrentMode, true, mCurrentMarker,
                getResources().getColor(R.color.transparent), getResources().getColor(R.color.common_green)));

        // 初始化搜索模块，注册搜索事件监听
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(this);

        // 初始化建议搜索模块，注册建议搜索事件监听
        mSuggestionSearch = SuggestionSearch.newInstance();
        mSuggestionSearch.setOnGetSuggestionResultListener(this);

        keyWorldsView = (AutoCompleteTextView) findViewById(R.id.searchkey);

//        sugAdapter = new ArrayAdapter<String>(this,
//                R.layout.item_dropdown_item, R.id.text1);
//        keyWorldsView.setAdapter(sugAdapter);
//        keyWorldsView.setThreshold(1);

        searchResultListAdapter = new LocationDemo3Adapter(this, searchResultList);
        keyWorldsView.setAdapter(searchResultListAdapter);
        keyWorldsView.setThreshold(1);
        /**
         * 当输入关键字变化时，动态更新建议列表
         */
        keyWorldsView.addTextChangedListener(new TextWatcher() {

            @Override
            public void afterTextChanged(Editable arg0) {

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {

            }

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2,
                                      int arg3) {
                if (cs.length() <= 0) {
                    return;
                }

                /**
                 * 使用建议搜索服务获取建议列表，结果在onSuggestionResult()中更新
                 */
                //还未定位到城市
                if (TextUtils.isEmpty(mCurrentCity)) {
                    return;
                }
                //根据关键字获取到列表
                mSuggestionSearch
                        .requestSuggestion((new SuggestionSearchOption())
                                .keyword(cs.toString()).city(mCurrentCity));
                //没有输入搜索内容
                if (TextUtils.isEmpty(keyWorldsView.getText().toString())) {
                    return;
                }
                //城市内搜索
                mPoiSearch.searchInCity((new PoiCitySearchOption())
                        .city(mCurrentCity).keyword(keyWorldsView.getText().toString()).pageNum(loadIndex));
            }
        });

        //搜索列表点击事件
        keyWorldsView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                address = searchResultList.get(position).key;
                latitude = searchResultList.get(position).pt.latitude + "";
                longitude = searchResultList.get(position).pt.longitude + "";
                keyWorldsView.setText(address + "");
                if (!TextUtils.isEmpty(address)) {
                    keyWorldsView.setSelection(address.length());
                }
                LogUtils.e(address + " " + latitude + " " + longitude);
            }
        });
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        double x = sensorEvent.values[SensorManager.DATA_X];
        if (Math.abs(x - lastX) > 1.0) {
            mCurrentDirection = (int) x;
            locData = new MyLocationData.Builder()
                    .accuracy(mCurrentAccracy)
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(mCurrentLat)
                    .longitude(mCurrentLon).build();
            mBaiduMap.setMyLocationData(locData);
        }
        lastX = x;

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    @OnClick({R.id.back, R.id.next})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                Utils.hideSoftKeyboard(LocationDemo3.this, back);
                JumpHelper.finish(LocationDemo3.this);
                break;
            case R.id.next:
                if (TextUtils.isEmpty(address)) {
                    showToast("请输入正确的地址");
                } else {
                    Intent intent = new Intent();
                    //经纬度和详细地址
                    intent.putExtra("latitude", latitude);
                    intent.putExtra("longitude", longitude);
                    intent.putExtra("address", address);
                    setResult(RESULT_OK, intent);
                    Utils.hideSoftKeyboard(LocationDemo3.this, back);
                    JumpHelper.finish(LocationDemo3.this);
                }
                break;
        }
    }

    private boolean hasRequestedData = false;

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            mCurrentLat = location.getLatitude();
            mCurrentLon = location.getLongitude();
            //城市
            if (TextUtils.isEmpty(mCurrentCity))
                mCurrentCity = location.getCity();
            LogUtils.e("location city:" + mCurrentCity);
            mCurrentAccracy = location.getRadius();
            locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(13.5f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

    /**
     * 污染源集合
     */
    private List<DepartmentAreaReturn.DataBean> dataList = new ArrayList<DepartmentAreaReturn.DataBean>();

    public void initOverlay() {
        if (dataList == null) {
            return;
        }
        //清除所有Overlay
        mBaiduMap.clear();
        for (int i = 0; i < dataList.size(); i++) {
            double lat = 0;
            double lng = 0;
            LatLng latLng = new LatLng(mCurrentLat, mCurrentLon);

            BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory
                    .fromResource(R.mipmap.ic_ditu_dingweidian);
            MarkerOptions markerOptions = new MarkerOptions().position(latLng).icon(bitmapDescriptor)
                    .zIndex(9).draggable(true);
            final Marker marker = (Marker) (mBaiduMap.addOverlay(markerOptions));
            View view = LayoutInflater.from(this).inflate(R.layout.pupopwindow_dingwei, null);
            TextView textView = (TextView) view.findViewById(R.id.tv_dingwei);
            textView.setText("" + marker.getPosition().describeContents());
            InfoWindow.OnInfoWindowClickListener listener = null;

            listener = new InfoWindow.OnInfoWindowClickListener() {
                public void onInfoWindowClick() {
                    LatLng ll = marker.getPosition();
                    LatLng llNew = new LatLng(ll.latitude + 0.005,
                            ll.longitude + 0.005);
                    marker.setPosition(llNew);
                    mBaiduMap.hideInfoWindow();
                }
            };
            LatLng ll = marker.getPosition();
            InfoWindow mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(view), ll, -47, listener);
            mBaiduMap.showInfoWindow(mInfoWindow);
        }
    }

    /**
     * 将View转换成Bitmap
     *
     * @param addViewContent
     * @return
     */

    private Bitmap getViewBitmap(View addViewContent) {

        addViewContent.setDrawingCacheEnabled(true);

        addViewContent.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        addViewContent.layout(0, 0,
                addViewContent.getMeasuredWidth(),
                addViewContent.getMeasuredHeight());

        addViewContent.buildDrawingCache();
        Bitmap cacheBitmap = addViewContent.getDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

        return bitmap;
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
        //为系统的方向传感器注册监听器
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_UI);
    }

    @Override
    protected void onStop() {
        //取消注册传感器监听
        mSensorManager.unregisterListener(this);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();
    }


    /**
     * 响应城市内搜索按钮点击事件
     *
     * @param v
     */
    public void searchButtonProcess(View v) {
        searchType = 1;
        String citystr = mCurrentCity;
        String keystr = keyWorldsView.getText().toString();
        mPoiSearch.searchInCity((new PoiCitySearchOption())
                .city(citystr).keyword(keystr).pageNum(loadIndex));
    }

    /**
     * 响应周边搜索按钮点击事件
     *
     * @param v
     */
    public void searchNearbyProcess(View v) {
        searchType = 2;
        PoiNearbySearchOption nearbySearchOption = new PoiNearbySearchOption().keyword(keyWorldsView.getText()
                .toString()).sortType(PoiSortType.distance_from_near_to_far).location(center)
                .radius(radius).pageNum(loadIndex);
        mPoiSearch.searchNearby(nearbySearchOption);
    }

    public void goToNextPage(View v) {
        loadIndex++;
        searchButtonProcess(null);
    }

    /**
     * 响应区域搜索按钮点击事件
     *
     * @param v
     */
    public void searchBoundProcess(View v) {
        searchType = 3;
        mPoiSearch.searchInBound(new PoiBoundSearchOption().bound(searchbound)
                .keyword(keyWorldsView.getText().toString()));

    }


    /**
     * 获取POI搜索结果，包括searchInCity，searchNearby，searchInBound返回的搜索结果
     *
     * @param result
     */
    public void onGetPoiResult(PoiResult result) {
        if (result == null || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
//            Toast.makeText(LocationDemo3.this, "未找到结果", Toast.LENGTH_LONG)
//                    .show();
            return;
        }
        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            mBaiduMap.clear();
            PoiOverlay overlay = new MyPoiOverlay(mBaiduMap);
            mBaiduMap.setOnMarkerClickListener(overlay);
            overlay.setData(result);
            overlay.addToMap();
            overlay.zoomToSpan();

            switch (searchType) {
                case 2:
                    showNearbyArea(center, radius);
                    break;
                case 3:
                    showBound(searchbound);
                    break;
                default:
                    break;
            }

            return;
        }
        if (result.error == SearchResult.ERRORNO.AMBIGUOUS_KEYWORD) {

            // 当输入关键字在本市没有找到，但在其他城市找到时，返回包含该关键字信息的城市列表
            String strInfo = "在";
            for (CityInfo cityInfo : result.getSuggestCityList()) {
                strInfo += cityInfo.city;
                strInfo += ",";
            }
            strInfo += "找到结果";
//            Toast.makeText(LocationDemo3.this, strInfo, Toast.LENGTH_LONG)
//                    .show();
        }
    }

    /**
     * 获取POI详情搜索结果，得到searchPoiDetail返回的搜索结果
     *
     * @param result
     */
    public void onGetPoiDetailResult(PoiDetailResult result) {
        if (result.error != SearchResult.ERRORNO.NO_ERROR) {
//            Toast.makeText(LocationDemo3.this, "抱歉，未找到结果", Toast.LENGTH_SHORT)
//                    .show();
        } else {
            //经纬度和地址
            latitude = result.getLocation().latitude + "";
            longitude = result.getLocation().longitude + "";
            address = result.getAddress();
            LogUtils.e("address:" + address + "latitude:" + latitude + " longitude:" + longitude);

            LatLng latLng = new LatLng(result.getLocation().latitude, result.getLocation().longitude);
            BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory
                    .fromResource(R.mipmap.ic_ditu_dingweidian);
            MarkerOptions markerOptions = new MarkerOptions().position(latLng).icon(bitmapDescriptor)
                    .zIndex(9).draggable(true);
            final Marker marker = (Marker) (mBaiduMap.addOverlay(markerOptions));
            marker.setAlpha(0);
            View view = LayoutInflater.from(this).inflate(R.layout.pupopwindow_dingwei, null);
            TextView textView = (TextView) view.findViewById(R.id.tv_dingwei);
            textView.setText("" + address);
            InfoWindow.OnInfoWindowClickListener listener = null;

            listener = new InfoWindow.OnInfoWindowClickListener() {
                public void onInfoWindowClick() {
                    LatLng ll = marker.getPosition();
                    LatLng llNew = new LatLng(ll.latitude + 0.005,
                            ll.longitude + 0.005);
                    marker.setPosition(llNew);
                    mBaiduMap.hideInfoWindow();
                }
            };
            LatLng ll = marker.getPosition();
            InfoWindow mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(view), ll, -47, listener);
            mBaiduMap.showInfoWindow(mInfoWindow);
        }
    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }

    /**
     * 获取在线建议搜索结果，得到requestSuggestion返回的搜索结果
     *
     * @param res
     */
    @Override
    public void onGetSuggestionResult(SuggestionResult res) {
        if (res == null || res.getAllSuggestions() == null) {
            return;
        }
        suggest = new ArrayList<String>();
        searchResultList = new ArrayList<SuggestionResult.SuggestionInfo>();
        for (SuggestionResult.SuggestionInfo info : res.getAllSuggestions()) {
            if (info.key != null) {
                suggest.add(info.key);
                searchResultList.add(info);
            }
        }
//        sugAdapter = new ArrayAdapter<String>(LocationDemo3.this, R.layout.item_dropdown_item, R.id.text1, suggest);
//        keyWorldsView.setAdapter(sugAdapter);
//        sugAdapter.notifyDataSetChanged();

        searchResultListAdapter = new LocationDemo3Adapter(this, searchResultList);
        keyWorldsView.setAdapter(searchResultListAdapter);
        searchResultListAdapter.notifyDataSetChanged();
    }

    private class MyPoiOverlay extends PoiOverlay {

        public MyPoiOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public boolean onPoiClick(int index) {
            super.onPoiClick(index);
            PoiInfo poi = getPoiResult().getAllPoi().get(index);
            // if (poi.hasCaterDetails) {
            mPoiSearch.searchPoiDetail((new PoiDetailSearchOption())
                    .poiUid(poi.uid));
            // }
            return true;
        }
    }

    /**
     * 对周边检索的范围进行绘制
     *
     * @param center
     * @param radius
     */
    public void showNearbyArea(LatLng center, int radius) {
        BitmapDescriptor centerBitmap = BitmapDescriptorFactory
                .fromResource(R.mipmap.ic_ditu_dingweidian);
        MarkerOptions ooMarker = new MarkerOptions().position(center).icon(centerBitmap);
        mBaiduMap.addOverlay(ooMarker);

        OverlayOptions ooCircle = new CircleOptions().fillColor(0xCCCCCC00)
                .center(center).stroke(new Stroke(5, 0xFFFF00FF))
                .radius(radius);
        mBaiduMap.addOverlay(ooCircle);
    }

    /**
     * 对区域检索的范围进行绘制
     *
     * @param bounds
     */
    public void showBound(LatLngBounds bounds) {
        BitmapDescriptor bdGround = BitmapDescriptorFactory
                .fromResource(R.mipmap.ic_ditu_dingweidian);

        OverlayOptions ooGround = new GroundOverlayOptions()
                .positionFromBounds(bounds).image(bdGround).transparency(0.8f);
        mBaiduMap.addOverlay(ooGround);

        MapStatusUpdate u = MapStatusUpdateFactory
                .newLatLng(bounds.getCenter());
        mBaiduMap.setMapStatus(u);

        bdGround.recycle();
    }
}
